package com.adpter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import u.aly.co;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.common.method.ServerPath;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chatuidemo.activity.ShowBigImage;
import com.easemob.chatuidemo.utils.ImageUtils;
import com.lidroid.xutils.BitmapUtils;
import com.matang.R;
import com.modle.Attach;

/**
 * @author py
 * 选择图片的GridViewAdapter
 *
 */
public class PyqGridViewAdapter extends BaseAdapter {

	private List<Attach> imgPaths = new ArrayList<Attach>();

	public List<Attach> getImgPaths() {
		return imgPaths;
	}

	private Context context;
	private int selectedPosition = 0;
	private BitmapUtils util;

	public PyqGridViewAdapter(Context context){
		this.context = context;
		//imgPaths.add("add");
		if (util == null) {
			util = new BitmapUtils(context);
		}

	}


	public int getCount() {

		return imgPaths.size(); 
	}


	public Attach getItem(int position) {

		return imgPaths.get(position);
	}


	public long getItemId(int position) {

		return position;
	}

	public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){   
		// 获得图片的宽高   
		int width = bm.getWidth();   
		int height = bm.getHeight();   
		// 计算缩放比例   
		float scaleWidth = ((float) newWidth) / width;   
		float scaleHeight = ((float) newHeight) / height;   
		// 取得想要缩放的matrix参数   
		Matrix matrix = new Matrix();   
		matrix.postScale(scaleWidth, scaleHeight);   

		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);   
		return newbm;   
	}  
	public View getView(int position, View convertView, ViewGroup parent) {


		ViewHolder  holder = null;
		if(convertView==null){
			convertView = LayoutInflater.from(context).inflate(R.layout.grid_item, null);
			holder = new ViewHolder();
			holder.imgPhoto =(ImageView) convertView.findViewById(R.id.imageview_ivMain);



			holder.imgPhoto.setScaleType(ScaleType.FIT_XY);
			holder.imgDelete = (ImageView) convertView.findViewById(R.id.imageview_ivSelect);
			convertView.setTag(holder);
		}
		else{
			holder=(ViewHolder)convertView.getTag();
		}
		holder.imgDelete.setImageBitmap(null);

		Log.i("test", "adapter----"+(imgPaths.size()-1)+"-----"+position);

		DisplayMetrics dm = context.getResources().getDisplayMetrics();

		int h =dm.heightPixels;
		int w = dm.widthPixels;
		LayoutParams params;
		params = holder.imgPhoto.getLayoutParams();
		params.height = (w-40)/4;
		params.width =  (w-40)/4;
		final String thumb = ServerPath.SERVER+imgPaths.get(position).getUrl();
		util.display(holder.imgPhoto, thumb);

		holder.imgPhoto.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				if (!thumb.contains("2015")) {
					return;
				}
				System.err.println("image view on click");
				String filePath = ImageUtils.getImagePath(thumb);
				Intent intent = new Intent(context, ShowBigImage.class);
				File file = new File(filePath);
				if (file.exists()) {
					Uri uri = Uri.fromFile(file);
					intent.putExtra("uri", uri);
					System.err.println("here need to check why download everytime");
				} else {
					// The local full size pic does not exist yet.
					// ShowBigImage needs to download it from the server
					// first
					// intent.putExtra("", message.get);
				//	ImageMessageBody body = (ImageMessageBody) message.getBody();
					intent.putExtra("secret", "");
					intent.putExtra("remotepath", thumb);
				}
//				if (message != null && message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
//						&& message.getChatType() != ChatType.GroupChat) {
//					try {
//						EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
//						message.isAcked = true;
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
				context.startActivity(intent);

			}
		});

		return convertView;
	}

	/**
	 * @author 删除点击项
	 *
	 */

	public static class ViewHolder{
		public ImageView imgPhoto;//图片

		public ImageView imgDelete;//删除标记
	}

	public void setSelectedPosition(int position) {   
		this.selectedPosition = position;
		notifyDataSetChanged();
	}
	public void addDatas(List<Attach> datas){
		this.imgPaths.addAll(datas);
		notifyDataSetChanged();
	}
	public void clearDatas(){
		imgPaths.clear();
		notifyDataSetChanged();
	}

	private Bitmap getImageThumbnail(String imagePath, int width, int height) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高，注意此处的bitmap为null
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		options.inJustDecodeBounds = false; // 设为 false
		// 计算缩放比
		int h = options.outHeight;
		int w = options.outWidth;
		int beWidth = w / width;
		int beHeight = h / height;
		int be = 1;
		if (beWidth < beHeight) {
			be = beWidth;
		} else {
			be = beHeight;
		}
		if (be <= 0) {
			be = 1;
		}
		options.inSampleSize = be;
		// 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
		bitmap = BitmapFactory.decodeFile(imagePath, options);
		// 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}


}
